<!-- Metaverse City Component -->
<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import CityScene from '../metaverse/scenes/CityScene';
import { store } from '../metaverse/utils/store';
import api from '../metaverse/utils/api';
import socketService from '../metaverse/utils/socket';

// Container reference for the 3D scene
const container = ref(null);
const cityScene = ref(null);

// UI state
const showCarDetails = ref(false);
const showDealerInfo = ref(false);
const showChat = ref(false);
const chatMessage = ref('');

// Controls instructions
const showControls = ref(true);

// Initialize the 3D scene
onMounted(async () => {
  console.log('MetaverseCity component mounted');
  
  // Set default user data
  const userData = { id: 1, username: 'Player', token: 'dummy-token' };
  localStorage.setItem('token', userData.token);
  store.setUser(userData);
  
  // Connect to socket (for multiplayer)
  socketService.connect(userData.id, userData.username);
  
  // Initialize 3D scene after DOM is ready
  await nextTick();
  await initScene();
  
  // Auto-hide controls after 10 seconds
  setTimeout(() => {
    showControls.value = false;
  }, 10000);
});

// Clean up on component unmount
onUnmounted(() => {
  console.log('MetaverseCity component unmounting, cleaning up resources');
  
  // Disconnect from socket
  socketService.disconnect();
  
  // Clean up event listeners
  if (cityScene.value) {
    window.removeEventListener('resize', cityScene.value.onWindowResize);
    document.removeEventListener('keydown', cityScene.value.onKeyDown);
    document.removeEventListener('keyup', cityScene.value.onKeyUp);
    if (container.value) {
      container.value.removeEventListener('click', cityScene.value.onMouseClick);
    }
  }
  
  // Remove global reference
  if (window.cityScene) {
    window.cityScene = null;
  }
});

// Initialize scene after login
async function initScene() {
  console.log('Initializing scene');
  
  if (!container.value) {
    console.error('Container reference is not available');
    return;
  }
  
  console.log('Container reference available, creating scene');
  console.log('Container dimensions:', container.value.clientWidth, container.value.clientHeight);
  
  try {
    cityScene.value = new CityScene(container.value);
    
    // Make city scene globally available for other components
    window.cityScene = cityScene.value;
    
    // Load data after scene is created
    await loadMetaverseData();
  } catch (error) {
    console.error('Error initializing 3D scene:', error);
  }
}

// Load cars and dealers from the API
async function loadMetaverseData() {
  console.log('Loading metaverse data');
  try {
    // Fetch cars
    const cars = await api.getCars();
    console.log('Loaded cars:', cars);
    if (cityScene.value) {
      cityScene.value.populateCars(cars);
    }
    
    // Fetch dealers
    const dealers = await api.getDealers();
    console.log('Loaded dealers:', dealers);
    if (cityScene.value) {
      cityScene.value.populateDealers(dealers);
    }
  } catch (error) {
    console.error('Error loading metaverse data:', error);
  }
}

// Toggle control help visibility
function toggleControls() {
  showControls.value = !showControls.value;
}

// Watch for car selection
watch(() => store.selectedCar, (newCar) => {
  if (newCar) {
    showCarDetails.value = true;
    showDealerInfo.value = false;
  } else {
    showCarDetails.value = false;
  }
});

// Watch for dealer selection
watch(() => store.selectedDealer, (newDealer) => {
  if (newDealer) {
    showDealerInfo.value = true;
    showCarDetails.value = false;
  } else {
    showDealerInfo.value = false;
  }
});

// Send chat message
function sendMessage() {
  if (!chatMessage.value.trim()) return;
  
  socketService.sendChatMessage(chatMessage.value, store.selectedDealer?.dealer_id);
  chatMessage.value = '';
}

// Close car details panel
function closeCarDetails() {
  showCarDetails.value = false;
  store.selectCar(null);
}

// Close dealer info panel
function closeDealerInfo() {
  showDealerInfo.value = false;
  showChat.value = false;
  store.selectDealer(null);
}

// Toggle chat panel
function toggleChat() {
  showChat.value = !showChat.value;
}

// Schedule appointment with dealer
async function scheduleAppointment() {
  if (!store.selectedCar || !store.selectedDealer) {
    return;
  }
  
  try {
    const appointmentTime = new Date();
    appointmentTime.setDate(appointmentTime.getDate() + 1); // Tomorrow
    
    await api.scheduleAppointment(
      store.selectedCar.car_id,
      store.selectedDealer.dealer_id,
      appointmentTime.toISOString()
    );
    
    alert('Appointment scheduled successfully!');
  } catch (error) {
    console.error('Error scheduling appointment:', error);
    alert('Failed to schedule appointment. Please try again.');
  }
}
</script>

<template>
  <div class="metaverse-container">
    <!-- 3D scene container -->
    <div class="scene-container" ref="container"></div>
    
    <!-- Car details panel -->
    <div v-if="showCarDetails" class="details-panel car-details">
      <button class="close-button" @click="closeCarDetails">×</button>
      <h3>{{ store.selectedCar.title || store.selectedCar.brand + ' ' + store.selectedCar.model }}</h3>
      
      <div class="car-info">
        <div class="info-item">
          <span class="label">Brand:</span> 
          <span class="value">{{ store.selectedCar.brand }}</span>
        </div>
        
        <div class="info-item">
          <span class="label">Model:</span> 
          <span class="value">{{ store.selectedCar.model }}</span>
        </div>
        
        <div class="info-item">
          <span class="label">Type:</span> 
          <span class="value">{{ store.selectedCar.car_type }}</span>
        </div>
        
        <div class="info-item">
          <span class="label">Price:</span> 
          <span class="value">${{ store.selectedCar.selling_price }}</span>
        </div>
        
        <div class="info-item">
          <span class="label">Year:</span> 
          <span class="value">{{ new Date(store.selectedCar.produce_time).getFullYear() }}</span>
        </div>
        
        <div class="info-item">
          <span class="label">Color:</span> 
          <span class="value">{{ store.selectedCar.color }}</span>
        </div>
        
        <div class="info-item">
          <span class="label">Mileage:</span> 
          <span class="value">{{ store.selectedCar.mileage }} miles</span>
        </div>
      </div>
      
      <div class="car-description">
        <h4>Description</h4>
        <p>{{ store.selectedCar.description || 'No description available.' }}</p>
      </div>
      
      <button class="action-button contact-dealer">
        Contact Dealer
      </button>
    </div>
    
    <!-- Dealer info panel -->
    <div v-if="showDealerInfo" class="details-panel dealer-info">
      <button class="close-button" @click="closeDealerInfo">×</button>
      <h3>{{ store.selectedDealer.dealer_name }}</h3>
      
      <div class="dealer-details">
        <div class="info-item">
          <span class="label">Contact:</span> 
          <span class="value">{{ store.selectedDealer.contact_person }}</span>
        </div>
        
        <div class="info-item">
          <span class="label">Phone:</span> 
          <span class="value">{{ store.selectedDealer.contact_phone }}</span>
        </div>
        
        <div class="info-item">
          <span class="label">Address:</span> 
          <span class="value">{{ store.selectedDealer.address }}</span>
        </div>
        
        <div class="info-item">
          <span class="label">Rating:</span> 
          <span class="value">{{ store.selectedDealer.rating }} / 5</span>
        </div>
      </div>
      
      <div class="dealer-actions">
        <button class="action-button" @click="toggleChat">
          {{ showChat ? 'Hide Chat' : 'Chat with Dealer' }}
        </button>
        
        <button class="action-button" @click="scheduleAppointment" :disabled="!store.selectedCar">
          Schedule Appointment
        </button>
      </div>
      
      <!-- Chat panel -->
      <div v-if="showChat" class="chat-panel">
        <div class="chat-messages">
          <div 
            v-for="(message, index) in store.chatMessages" 
            :key="index" 
            :class="['message', message.senderId === store.user.id ? 'sent' : 'received']"
          >
            <div class="message-sender">{{ message.senderName }}</div>
            <div class="message-content">{{ message.message }}</div>
            <div class="message-time">{{ new Date(message.timestamp).toLocaleTimeString() }}</div>
          </div>
          
          <div v-if="store.chatMessages.length === 0" class="empty-chat">
            No messages yet. Start the conversation!
          </div>
        </div>
        
        <div class="chat-input">
          <input 
            type="text" 
            v-model="chatMessage" 
            placeholder="Type your message..." 
            @keyup.enter="sendMessage"
          />
          <button @click="sendMessage">Send</button>
        </div>
      </div>
    </div>
    
    <!-- Connected users display -->
    <div class="connected-users">
      <h4>Users Online: {{ store.connectedUsers.length }}</h4>
      <ul>
        <li v-for="user in store.connectedUsers" :key="user.id">
          {{ user.username }}
        </li>
      </ul>
    </div>
    
    <!-- Controls help -->
    <div class="controls-help" v-if="showControls" @click="toggleControls">
      <h4>控制说明</h4>
      <p>WASD或方向键: 移动</p>
      <p>右键按住拖动: 旋转视角</p>
      <p>双击场景: 锁定鼠标 (更精确控制)</p>
      <p>F键: 与物体交互</p>
      <p>ESC: 退出鼠标锁定</p>
      <p>V键: 切换第一/第三人称视角</p>
      <p>左键点击: 与物体交互</p>
      <p>(点击此面板隐藏)</p>
    </div>
    
    <!-- System messages -->
    <div class="system-messages" v-if="store.systemMessages.length > 0">
      <div 
        v-for="message in store.systemMessages" 
        :key="message.id" 
        class="system-message"
      >
        {{ message.message }}
      </div>
    </div>
    
    <!-- Toggle controls button (visible when controls are hidden) -->
    <button class="toggle-controls" v-if="!showControls" @click="toggleControls">
      显示控制说明
    </button>
  </div>
</template>

<style scoped>
.metaverse-container {
  width: 100%;
  height: 100vh;
  position: relative;
  overflow: hidden;
}

.scene-container {
  width: 100%;
  height: 100%;
  background-color: #000; /* Add dark background during loading */
}

.details-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 300px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  padding: 1rem;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  max-height: calc(100vh - 40px);
  overflow-y: auto;
}

.close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  background: transparent;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #555;
}

.details-panel h3 {
  margin-top: 0;
  color: #333;
  padding-right: 30px;
}

.info-item {
  display: flex;
  margin-bottom: 0.5rem;
}

.label {
  font-weight: bold;
  width: 80px;
}

.car-description, .dealer-details {
  margin-top: 1rem;
}

.car-description h4 {
  margin-top: 0;
  color: #333;
}

.action-button {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 1rem;
  transition: background-color 0.3s;
  width: 100%;
}

.action-button:hover {
  background-color: #2980b9;
}

.action-button:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.dealer-actions {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.connected-users {
  position: absolute;
  top: 20px;
  left: 20px;
  background-color: rgba(255, 255, 255, 0.7);
  padding: 1rem;
  border-radius: 10px;
  max-width: 200px;
}

.connected-users h4 {
  margin-top: 0;
  margin-bottom: 0.5rem;
}

.connected-users ul {
  padding-left: 1.5rem;
  margin: 0;
}

.controls-help {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 1rem;
  border-radius: 10px;
  cursor: pointer;
}

.controls-help h4 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #3498db;
}

.controls-help p {
  margin: 0.2rem 0;
}

.toggle-controls {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
}

.system-messages {
  position: absolute;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  pointer-events: none;
}

.system-message {
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 20px;
  font-size: 16px;
  animation: fadeIn 0.3s ease-in, fadeOut 0.5s ease-out 2.5s forwards;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes fadeOut {
  from { opacity: 1; }
  to { opacity: 0; }
}
</style> 